package com.example.dynamicjavacode.util;

import javax.tools.SimpleJavaFileObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;

public class MyJavaClassFileObject extends SimpleJavaFileObject {
    //java class 字节流
    private ByteArrayOutputStream outputStream = null;
    //java 源代码
    private String contents = null;
    //java 全限定类名
    private String className;

    public MyJavaClassFileObject(String name, Kind kind) {
        super(URI.create("string:///" + name.replace('.', '/') + kind.extension), kind);
        this.outputStream = new ByteArrayOutputStream();
    }

    public MyJavaClassFileObject(String className, String contents) {
        super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
        this.className = className;
        this.contents = contents;
    }

    public byte[] getBytes() {
        return outputStream.toByteArray();
    }

    //编译时候会调用openOutputStream获取输出流,并写数据
    @Override
    public OutputStream openOutputStream() throws IOException {
        return outputStream;
    }

    //编译时会调用获取Java源代码进行编译
    public CharSequence getCharContent(boolean ignoredEncodingErrors) throws IOException {
        return contents;
    }

    public String getClassName() {
        return className;
    }
}